<?php
namespace App\Repositories;


use App\Interfaces\CouponService;
use App\Interfaces\DiscountService;
use App\Interfaces\OrderService;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Exceptions\Interfaces\OrderServiceException;
use App\Exceptions\Interfaces\OrderGoodsServiceException;

use App\Models\Goods;
use App\Models\Address;
use DB,Auth,Log;
use App\Services\CustomsClearance;
use App\Services\Eto\EtoClient;
use App\Services\Eto\EtoClientNew;
use App\Services\Yto\YtoClient;
use App\Services\Etouch\EtouchClient;
use App\Services\Etouch\EtouchClientOld;
use App\Services\Eto\EtoClientException;
use App\Models\Shop;
use App\Jobs\CancelOrders;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Models\GoodsContent;
use App\Interfaces\StockService;
use App\Interfaces\GoodsStockHistoryService;
use App\Interfaces\PushTarrifService;
use App\Services\AlipayCustoms\AlipayCustom;
use App\Services\AlipayCustoms\AlipayCustomsException;

use App\Services\Etouch\EtouchClientException;
use App\Models\User;
use App\Models\Discount;
use App\Models\UserCoupon;

// use Latrell\Wxpay\Models\UnifiedOrder;
use App\Services\Wxpay\Models\PushCustoms;
use App\Services\Wxpay\Wxpay;
use App\Services\Wxpay\WxpayException;
use App\Services\Wxpay\Models\Refund;

class OrderRepository  implements OrderService{

    use DispatchesJobs;

    public function __construct(
        EtoClient $etoClient,
        EtoClientNew $etoClientNew,
        YtoClient $ytoClient,
        EtouchClient $etouchClient,
        EtouchClientOld $etouchClientOld,
        StockService $stockService,
        GoodsStockHistoryService $goodsStockHistoryService,
        PushTarrifService $pushTarrifService,
        AlipayCustom $alipayCustom,
        CustomsClearance $customsClearance,
        CouponService $couponService,
        DiscountService $discountService
    ){


        $this->etoClient = $etoClient;
        $this->etoClientNew = $etoClientNew;
        $this->ytoClient = $ytoClient;
        $this->etouchClient = $etouchClient;
        $this->etouchClientOld = $etouchClientOld;
        $this->stockService = $stockService;
        $this->goodsStockHistoryService = $goodsStockHistoryService;
        $this->pushTarrifService = $pushTarrifService;
        $this->customsClearance = $customsClearance;
        $this->alipayCustom = $alipayCustom;
        $this->customsClearance = new CustomsClearance();
        $this->couponService = $couponService;
        $this->discountService = $discountService;

    }



    // public function getBuyGoodsInfo(Array $goods,$address_id=0,Array $coupons=[],Array $discounts=[],Array $current_discount_arr=[],$user_id=0){
    public function getBuyGoodsInfo(Array $goods, $address_id=0, Array $coupons=[], $user_id=0){


        $info = [];
        //拼出goods_id=>buy_num形式
        $buyGoods = [];
        foreach($goods as $k=>$v){
            $buyGoods[$v['goods_id']]=$v['buy_num'];
        }


        $devides = $this->devide($goods);

        $orders = [];

        //购买数量
        $info['buyGoods'] = $buyGoods;
        $info['total_tariff_fee'] = 0.00;
        $info['total_buy_number'] = 0.00;
        $info['total_shipping_fee'] = 0.00;
        $info['total_order_price'] = 0.00;
        $info['total_pay_price'] = 0.00;
        $info['total_coupon_price'] = 0.00;
        $info['total_discount_price'] = 0.00;

        foreach ($devides as $k=>$devide) {

            //计算
            $calculate = $this->calculateOrderGoods($devide['type'], $devide['orderGoods'],  $buyGoods,  $address_id, $coupons, $user_id);

            //订单商品
            $orders[$k]['orderGoods'] = $devide['orderGoods'];

            $orders[$k]['coupons'] = $this->couponService->getCanUseCoupon($user_id,$devide['orderGoods'],$buyGoods);

            //订单计算
            $orders[$k]['caculator'] = $calculate;
            //订单类型
            $orders[$k]['type']=$devide['type'];
            //总计
            $info['total_tariff_fee'] += $calculate['total_tariff_fee'];
            $info['total_buy_number'] += $calculate['total_number'];
            $info['total_shipping_fee'] += $calculate['shipping_fee'];
            $info['total_order_price'] += $calculate['total_price'];
            $info['total_coupon_price'] += $calculate['coupon_price'];
            $info['total_discount_price'] += $calculate['total_discount_price'];
            $info['total_pay_price'] += $calculate['pay_price'];
        }

        //$info['total_pay_price'] = $info['total_pay_price']-$info['total_coupon_price'];

        //拆出E贸易商品和普通贸易


        $info['orders']['eshopGoods']=null;
        $info['orders']['cshopGoods']=null;
        foreach($orders as $order ){
            if ($order['type']==1){
                $info['orders']['eshopGoods']=$order;
            }elseif ($order['type']==0){
                $info['orders']['cshopGoods']=$order;
            }
        }

        return $info;
    }




    //计算商品
    // private function calculateOrderGoods($type, $orderGoods, $buyGoods, $address_id, Array $coupons, Array $discounts, $user_id=0){
    private function calculateOrderGoods($type, $orderGoods, $buyGoods, $address_id, Array $coupons, $user_id=0){

        $total_number = 0;
        $total_price = 0;
        $total_tariff_fee = 0;
        $calculate['total_discount_price'] = 0.00;        //限时折扣总金额
        $discount_total_number = 0;                       //使用限时折扣商品的数量

        foreach ($orderGoods as $goods) {

            $excise_tax = 0.00;

            $value_added_tax = 0.00;

            if ($goods->type==1){
                //$tariff_percent = $goods->tariff_percent;
                /*$excise_duty_percent = intval($goods->excise_duty_percent);//消费税
                $value_added_tax_percent = intval($goods->value_added_tax_percent);//增值税*/

                /*$excise_duty_percent = intval(empty($goods->recode_excise_duty_percent) ? $goods->excise_duty_percent : $goods->recode_excise_duty_percent);//消费税

                $value_added_tax_percent = intval(empty($goods->recode_value_added_tax_percent) ? $goods->value_added_tax_percent : $goods->recode_value_added_tax_percent);//增值税*/

                if ($goods->recode_excise_duty_percent == 0) {

                    $excise_duty_percent = 0;
                }elseif ($goods->recode_excise_duty_percent > 0) {

                    $excise_duty_percent = $goods->recode_excise_duty_percent;
                }elseif ($goods->recode_excise_duty_percent < 0) {

                    $excise_duty_percent = $goods->excise_duty_percent;
                }else{

                    $excise_duty_percent = $goods->excise_duty_percent;
                }

                if ($excise_duty_percent) {
                    /**
                     * 消费税=（完税价格+关税）/（1-消费税率）*消费税率*70%=1/(1-0.15）*0.15*0.7=0.123529
                     * 增值税=（完税价格+关税+消费税）*0.17*0.7=（1+0+0.17647）*0.17*0.7=0.13999
                     * （注：完税价格为固定值1，关税为固定值0）
                     *
                     * 含消费税的综合税率=消费税+增值税=0.123529+0.13999=0.263519=0.2635
                     * 不含消费税的综合税率=0.119
                     *
                     * 注：计算增值税时，消费税要全额计算，不是0.7之后的消费税
                     *
                     * 商品的综合税率 = 消费税 + 增值税；
                     * 商品的税金 = 商品价格 * 商品数量 * 综合税率。（订单中产生的关税）
                     */
                    $excise_tax = 1 / (1 - $excise_duty_percent / 100) * $excise_duty_percent / 100 * 70 / 100;                 //消费税
                }

                $value_added_tax = (1 + 0 + $excise_tax * 100 / 70) * 17 / 100 * 70 / 100;         //增值税

                if (isset($goods['discount']) && $goods['discount']) {


                    /*$eDiscountPrice = $goods->shop_price * intval(100 - $goods['discount']['discount_value']) / 100 * $buyGoods[$goods->goods_id];

                    $eDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", $eDiscountPrice), 0, -1));

                    $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100), 0, -1));*/

                    $eDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", ($goods->shop_price - $goods->goods_real_price) * $buyGoods[$goods->goods_id]), 0, -1));

                    $calculate['total_discount_price'] += $eDiscountPrice;


                    $discount_total_number += $buyGoods[$goods->goods_id];
                }

            }else{
                //$tariff_percent = 0;
                $excise_duty_percent=0;
                $value_added_tax_percent=0;

                if (isset($goods['discount']) && $goods['discount']) {


                    /*$cDiscountPrice = $goods->shop_price * intval(100 - $goods['discount']['discount_value']) / 100 * $buyGoods[$goods->goods_id];

                    $cDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", $cDiscountPrice), 0, -1));

                    $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100), 0, -1));*/

                    $cDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", ($goods->shop_price - $goods->goods_real_price) * $buyGoods[$goods->goods_id]), 0, -1));

                    $calculate['total_discount_price'] += $cDiscountPrice;

                    $discount_total_number += $buyGoods[$goods->goods_id];
                }
            }

            //计算商品总数
            $total_number += $buyGoods[$goods->goods_id];

            //计算总价
            $total_price += $goods->shop_price * $buyGoods[$goods->goods_id];

            $consolidated_tax = $excise_tax + $value_added_tax;                                             //综合税

            //计算总关税

            // $total_tariff_fee += $goods->goods_real_price*$buyGoods[$goods->goods_id]*($excise_duty_percent/100+$value_added_tax_percent/100)*70/100;

            $total_tariff_fee += $goods->goods_real_price * $buyGoods[$goods->goods_id] * $consolidated_tax;

        }//end foreach()

        $calculate['total_discount_price'] = sprintf("%.2f",substr(sprintf("%.3f", $calculate['total_discount_price']), 0, -1));
        $calculate['total_number'] = (integer)$total_number;
        $calculate['total_item'] = (integer)count($orderGoods);//订单中商品种类
        $calculate['total_price'] = sprintf("%.2f",substr(sprintf("%.3f", $total_price), 0, -1));
        $calculate['total_tariff_fee'] = sprintf("%.2f",substr(sprintf("%.3f", $total_tariff_fee), 0, -1));
        // $calculate['total_tariff_fee'] = sprintf("%.2f",sprintf("%.3f", $total_tariff_fee));
        $calculate['discount_total_number'] = (integer)$discount_total_number;

        //TODO 关税问题
        //if ($calculate['total_tariff_fee']<=50) $calculate['total_tariff_fee'] = 0.00;

        // $calculate['shipping_fee'] = $this->getShippingFee($type,$address_id,$total_price);

        $no_coupon_price = $calculate['total_price'] + $calculate['total_tariff_fee'] - $calculate['total_discount_price'];

        $calculate['coupon_price'] = 0.00;

        //E贸易优惠券
        if ($type==1&&isset($coupons['e_coupon_id'])&&intval($coupons['e_coupon_id'])!=0&&intval($user_id)!=0){
            $coupon = $this->couponService->getUserCouponInfo($coupons['e_coupon_id'],$user_id);
            if ($coupon) {
                $eCouponPrice = $coupon->value > $no_coupon_price ? $no_coupon_price : $coupon->value;
                $calculate['coupon_price'] += $eCouponPrice;
            }
        }

        //一般贸易优惠券
        if ($type==0&&isset($coupons['c_coupon_id'])&&intval($coupons['c_coupon_id'])!=0&&intval($user_id)!=0){
            $coupon = $this->couponService->getUserCouponInfo($coupons['c_coupon_id'],$user_id);
            if ($coupon){
                $cCouponPrice =$coupon->value > $no_coupon_price ? $no_coupon_price : $coupon->value;
                $calculate['coupon_price']+=$cCouponPrice;
            }

        }

        $no_shipping_fee_price = $no_coupon_price - $calculate['coupon_price'];

        $no_shipping_fee_price = $no_shipping_fee_price > 0 ? $no_shipping_fee_price : 0.00;

        $calculate['shipping_fee'] = $this->getShippingFee($type,$address_id,$no_shipping_fee_price);

        $pay_price = $no_shipping_fee_price + $calculate['shipping_fee'];

        // $pay_price = sprintf("%.2f",substr(sprintf("%.3f", $pay_price), 0, -1));
        $pay_price = sprintf("%.2f",sprintf("%.3f", $pay_price));


        $calculate['pay_price'] = $pay_price > 0 ? $pay_price : 0.01;

        if ($pay_price>0) {
            # code...
            $calculate['pay_price'] = $pay_price;
        }else{

            $calculate['coupon_price'] -= 0.01;


            $calculate['pay_price'] = 0.01;
        }

// dd($calculate);
        return $calculate;

    }


    /** 创建订单
     * @param $user_id
     * @param array $goods
     * @param $address_id
     * @param $payType
     * @param string $shippingMessage
     * @param string $invoiceMessage
     * @param string $orderMessage
     * @param string $create_order_device       //下单的设备，0：web端下单，1：客户端下单
     * @param string $is_all_goods_exception    //是否抛出所有商品的异常信息，0：不抛出所有的商品异常，只抛出第一个商品的第一个异常；1：抛出所有的商品异常
     * @param string $pay_type       //支付类型，pay_type:支付宝支付; wxpay:微信支付; pinganpay:平安支付;
     * @return mixed
     * @throws OrderServiceException
     */
    // public function createOrder($user_id, Array $buyGoods, $address_id,Array $coupons,Array $discounts=[], $create_order_device=0, $is_all_goods_exception = 0){
    public function createOrder($user_id, Array $buyGoods, $address_id, Array $coupons, $create_order_device=0, $is_all_goods_exception = 0, $pay_type = ''){


        //1 验证


        $order_ids = [];

        $cartGoods = [];
        foreach($buyGoods as $k=>$v){
            $cartGoods[$v['goods_id']]=$v['buy_num'];
        }

        if ($pay_type) {

            switch ($pay_type) {
                case 1:
                    $pay_type = 'alipay';
                    break;

                case 3:
                    $pay_type = 'wxpay';
                    break;

                case 4:
                    $pay_type = 'pinganpay';
                    break;
            }
        }

        DB::beginTransaction();//开启事务,开始批量操作
        try {

            //根据商品分店铺,分类型成订单

            $devides = $this->devide($buyGoods);

            $use_same_discount_amount = 0;

            $is_has_exception = false;              //是否有商品库存不足或已下架异常

            if ($is_all_goods_exception) {

                $exception_arr = [
                    'not_on_sale' => [],
                    'not_goods_number' => []
                ];

            }


            foreach($devides as $k=>$devide){


                $caculator = $this->calculateOrderGoods($devide['type'], $devide['orderGoods'], $cartGoods, $address_id, $coupons, $user_id);


//                //E贸易关税限额 规则:如果订单商品只有1个,并且价格超过1000,订单价格超过1000能下单
//
//                if ($devide['type']==1&&$caculator['total_price']>1000){
//
//                    if (!$caculator['total_item']==1&&$caculator['total_number']==1){
//                        throw new OrderServiceException("E贸易商品订单总价超过1000元,请调整您的订单");
//
//                    }
//                }


               if ($devide['type']==1&&($caculator['total_price'] - $caculator['total_discount_price'])>1000){

                    throw new OrderServiceException("E贸易商品订单总价超过1000元,请调整您的订单");

               }

                $user_coupon_id = 0;

                $coupon_id = 0;


                //e贸易优惠券扣除
                if ($devide['type']==1&&isset($coupons['e_coupon_id'])&&intval($coupons['e_coupon_id'])!=0&&intval($user_id)!=0){

                    $this->couponService->useCoupon($user_id,$coupons['e_coupon_id']);

                    $user_coupon_id = $coupons['e_coupon_id'];

                }

                //一般贸易优惠券扣除
                if ($devide['type']==0&&isset($coupons['c_coupon_id'])&&intval($coupons['c_coupon_id'])!=0&&intval($user_id)!=0){

                    $this->couponService->useCoupon($user_id,$coupons['c_coupon_id']);

                    $user_coupon_id = $coupons['c_coupon_id'];

                }

                if ($user_coupon_id) {

                    $user_coupon = UserCoupon::find($user_coupon_id);

                    if ($user_coupon) {

                        $coupon_id = $user_coupon->coupon_id;
                    }
                }


                $address = Address::find($address_id);

                $order = new Order();
                $order->order_sn = $this->makeOrderSn();
                $order->user_id = $user_id;
                $order->coupon_id = $coupon_id;
                $order->add_time = date('Y-m-d H:i:s');
                $order->order_status = 1;//已下单
                $order->order_type = $devide['type'];//类型
                $order->shop_id = '';//店铺ID
                $order->order_price = $caculator['total_price'];
                $order->shipping_fee = $caculator['shipping_fee'];
                $order->order_tariff_fee = $caculator['total_tariff_fee'];
                $order->total_goods_number = $caculator['total_number'];
                $order->pay_price = $caculator['pay_price'];
                $order->discount_price = $caculator['total_discount_price'];
                $order->coupon_price = $caculator['coupon_price'];
                $order->country = $address->country;//
                $order->province = $address->province;//
                $order->city = $address->city;//
                $order->district = $address->district;//
                $order->address = $address->address;//
                $order->consignee = $address->consignee;//
                $order->mobile = $address->mobile;//
                $order->id_type = 1;//
                $order->id_card = $address->id_card;//
                $order->shipping_type = '';//
                $order->shipping_num ='' ;//
                $order->shipping_time;//
                $order->shipping_message;//
                $order->create_order_device = $create_order_device;//
                $order->pay_type = $pay_type;//
                // dd($order);
                $order->save();


                if ($order->order_id){

                    foreach($devide['orderGoods'] as $k=>$v){

                        if ($v->is_on_sale!=1||!is_null($v->deleted_at)){

                            if ($is_all_goods_exception) {

                                $exception_arr['not_on_sale'][] = $v->goods_id;

                                $is_has_exception = true;
                            }else{

                                throw new OrderServiceException("商品{$v->goods_name}已下架");
                            }
                        }

                        if($cartGoods[$v->goods_id]>$v->goods_number){

                            if ($is_all_goods_exception) {

                                $exception_arr['not_goods_number'][] = $v->goods_id;

                                $is_has_exception = true;
                            }else{

                                throw new OrderServiceException("商品{$v->goods_name}库存不足");
                            }
                        }

                        //去库存
                        $this->stockService->updateStock($v->goods_id, $user_id, $cartGoods[$v->goods_id], 'reduce', '用户下单减库存', $this->goodsStockHistoryService, $is_all_goods_exception);


                        $goodsContent = GoodsContent::find($v->goods_id);
                        if ($goodsContent) {

                            $goods_content = $goodsContent->goods_content;
                        } else {

                            $goods_content = '';
                        }//end if()

                        //增加销量
                        $goods = Goods::find($v->goods_id);
                        $goods->sales_num = $goods->sales_num + $cartGoods[$v->goods_id];
                        $goods->save();


                        /*if (isset($v->discount) && $v->discount) {

                            $discountPrice = $v->shop_price * intval(100 - $v->discount['discount_value']) / 100 * $cartGoods[$v->goods_id];

                            $discountPrice = sprintf("%.2f",substr(sprintf("%.3f", $discountPrice), 0, -1));

                            $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $v->shop_price * intval($v->discount['discount_value']) / 100), 0, -1));
                        }else{

                            $goods_real_price = $v->shop_price;
                        }*/

                        $order_goods_id = OrderGoods::insertGetId([
                            'order_id' => $order->order_id,
                            'goods_id' => $v->goods_id,
                            'goods_sn' => $v->goods_sn,
                            'goods_name' => $v->goods_name,
                            'goods_pet_name' => $v->goods_pet_name,
                            'goods_desc' => $v->goods_desc,
                            'buy_number' => $cartGoods[$v->goods_id],
                            'goods_weight' => $v->goods_weight,
                            'shop_price' => $v->shop_price,
                            'goods_real_price' => $v->goods_real_price,
                            'goods_discount_price' => $v->goods_real_price * intval($cartGoods[$v->goods_id]),
                            'tariff_percent' => $v->tariff_percent,
                            'goods_thumb' => $v->goods_thumb,
                            'shop_id' => $v->shop_id,
                            'cat_id' => $v->cat_id,
                            'type' => $v->type,
                            'brand_id' => $v->brand_id,
                            'goods_content' => $goods_content,
                            'resource' => $v->resource,
                            'add_time' => time()
                        ]);

                        if($order_goods_id==''){
                            throw new OrderServiceException("下单失败");
                        }
                    }

                    $order_ids[]=$order->order_id;
                }

            }

            if ($is_has_exception) {

                throw new OrderGoodsServiceException('部分商品已下架或库存不足', $exception_arr);
            }

        }catch (OrderServiceException $ex ){
            DB::rollback();
            throw new OrderServiceException($ex->getMessage());
        }

        DB::commit();

        foreach($order_ids as $order_id){

            $orderConfig = config('order-setting');
            $orderCancelTime = $orderConfig['order-cancel-time'];
            $this->dispatch((new CancelOrders($order_id))->delay($orderCancelTime));
        }//end foreach()
        return $order_ids;
    }

    public function deviceBuyGoods(Array $buyGoods){

        $devide = [];

        //拼出goods_id=>buy_num形式
        $cartGoods = [];
        foreach($buyGoods as $k=>$v){
            $cartGoods[$v['goods_id']]=$v['buy_num'];
        }

        $goodsIds = array_keys($cartGoods);//拆出商品ID


        //查询该商铺下跨境贸易商品
        $eshopGoods = Goods::join('category','category.cat_id','=','goods.cat_id')//关联分类
        ->whereIn('goods.goods_id',$goodsIds)//查询给定的商品
        ->where('goods.type',1)//E贸易条件
        ->get();

        if ($eshopGoods->count()>0) $devide[]=['type'=>1,'orderGoods'=>$eshopGoods];

        //查询该商铺下普通贸易商品
        $cshopGoods = Goods::join('category','category.cat_id','=','goods.cat_id')//关联分类
        ->whereIn('goods.goods_id',$goodsIds)//查询给定的商品
        ->where('goods.type',0)//普通贸易条件
        ->get();

        if ($cshopGoods->count()>0) $devide[]=['type'=>0,'orderGoods'=>$cshopGoods];

        return $devide;
    }

    /**
     * 根据商品ID数组,拆单成普通订单和E贸易订单
     * @param array $goods
     */
    private function devide(Array $goods){

        $devides = [];

        //拼出goods_id=>buy_num形式
        $cartGoods = [];
        foreach($goods as $k=>$v){
            $cartGoods[$v['goods_id']]=$v['buy_num'];
        }
        $goodsIds = array_keys($cartGoods);//拆出商品ID


        //查询该商铺下跨境贸易商品
        $eshopGoods = Goods::join('category','category.cat_id','=','goods.cat_id')//关联分类
        ->whereIn('goods.goods_id',$goodsIds)//查询给定的商品
        ->where('goods.type',1)//E贸易条件
        ->get();

        if ($eshopGoods->count()>0) $devides[]=['type'=>1,'orderGoods'=>$eshopGoods];

        //查询该商铺下普通贸易商品
        $cshopGoods = Goods::join('category','category.cat_id','=','goods.cat_id')//关联分类
        ->whereIn('goods.goods_id',$goodsIds)//查询给定的商品
        ->where('goods.type',0)//普通贸易条件
        ->get();

        if ($cshopGoods->count()>0) $devides[]=['type'=>0,'orderGoods'=>$cshopGoods];

        /*foreach ($devides as $k=>$devide) {

            //将所有的商品可用的最大折扣信息加入到商品里面
            foreach ($devide['orderGoods'] as $orderGoods_key => $orderGoods_value) {

                $devide['orderGoods'][$orderGoods_key]['discount'] = [];
                $devide['orderGoods'][$orderGoods_key]['goods_real_price'] = 0.00;        //商品折扣后的单价
                $devide['orderGoods'][$orderGoods_key]['goods_discount_price'] = 0.00;    //商品折扣的总金额

                $discount = $this->discountService->getCanUseBiggestDiscountByGoodsId($orderGoods_value->goods_id);

                if ($discount) {

                    $devide['orderGoods'][$orderGoods_key]['discount'] = $discount->toArray();

                    // $devide['orderGoods'][$orderGoods_key]['goods_real_price'] = sprintf("%.2f",substr(sprintf("%.3f", $orderGoods_value->shop_price * intval($orderGoods_value['discount']['discount_value']) / 100), 0, -1));
                    $devide['orderGoods'][$orderGoods_key]['goods_real_price'] = sprintf("%.2f",sprintf("%.3f", $orderGoods_value->shop_price * intval($orderGoods_value['discount']['discount_value']) / 100));

                    $devide['orderGoods'][$orderGoods_key]['goods_discount_price'] = $devide['orderGoods'][$orderGoods_key]['goods_real_price'] * intval($cartGoods[$orderGoods_value->goods_id]);
                }
            }
        }*/

        return $devides;

    }



    private function getShippingFee($type,$address_id,$orderPrice){

        //E贸易订单免邮费
        if ($type) return 0.0;

        //满60包邮
        if ($orderPrice>=config('shipping-price.freePostAmount')){

            return 0.00;
        }

        if (intval($address_id)==0){
            return 0.00;
        }


        $config = config('shipping-price');

        $specialArea = $config['specialArea'];
        //新疆西藏15  其他10

        $address = Address::find($address_id);

        if (in_array(str_replace(" ",'',$address->province),$specialArea)){

            return $config['special'];
        }else{
            return $config['postage'];

        }



    }


    public function getOrders($user_id){
        if(empty($user_id)){
            throw new OrderServiceException('用户id不能为空');
        }

        $order = Order::select('order.*','user.user_name','order_goods.goods_thumb')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->where('order.user_id',$user_id)
            ->groupBy('order.order_id')
            ->orderBy('order.add_time','desc')->paginate(10);

        return $order;
    }

    public function getOrdersByOrderStatus($user_id,$order_status){

        $order = Order::select('order.*','user.user_name','order_goods.goods_thumb')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->where('order.order_status',$order_status)
            ->groupBy('order.order_id')
            ->orderBy('order.add_time','desc')->get();
    }
    public function getOrdersByCommentStatus($user_id,$comment_status){
        $order = Order::select('order.*','user.user_name','order_goods.goods_thumb')
            ->join('user','order.user_id','=','user.id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->where('order.order_id')
            ->where('order.order_status',4)
            ->where('order_goods.comment_status',$comment_status)
            ->groupBy('order.order_id')
            ->orderBy('order.add_time','desc')->paginage(15);
    }


    public function countOrders($user_id,$status){
        $countorder = Order::select('order.*','user.user_name')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->join('user','order.user_id','=','user.id')
            ->where('order_goods.comment_status','=',0)
            ->where('order.user_id',$user_id)
            ->where('order.order_status',$status)
            ->groupBy('order.order_id')
            ->get()->count();
        return $countorder;
    }

    public function getOrderGoods($order_id){
        return $orderGoods = OrderGoods::select('order_goods.*','order.order_status')
            ->join('order','order.order_id','=','order_goods.order_id')
            ->where('order.order_id',$order_id)
            ->get();
    }
    public function getOrdershop($order_id){
        return $ordershop = Order::select('order.*','shop.id','shop.shop_name')
            ->join('shop','order.shop_id','=','shop.id')
            ->where('order.order_id',$order_id)
            ->first();
}
    public function getCancelOrders($user_id,$page_size=10){
        $canclOrder = Order::select('order.*','user.user_name')
            ->join('user','user.id','=','order.user_id')
            ->where('order.order_status','=','5')
            ->where('user.id',$user_id)
            ->orderBy('cancel_time', 'desc')
            ->paginate($page_size);
        return $canclOrder;

    }
    public function countCancelOrders($user_id){
        return $canclOrder = Order::select('order.*','user.user_name','order_goods.goods_thumb')
            ->join('user','user.id','=','order.user_id')
            ->join('order_goods','order_goods.order_id','=','order.order_id')
            ->where('order.order_status','=','5')
            ->where('user.id',$user_id)
            ->count();

    }

    public function countOrderGoods($order_id){
        $orderGoods = OrderGoods::select('order_goods.*','order.order_status')
            ->join('order','order.order_id','=','order_goods.order_id')
            ->where('order.order_id',$order_id)
            ->get();
        $GoodsNumArray = array();
        $orderGoodsNum=0;
        foreach($orderGoods as $key=>$value){
            $GoodsNumArray[$key] = $value->buy_number;
        }
        for($i=0;$i<count($GoodsNumArray);$i++){
            $orderGoodsNum = $orderGoodsNum + $GoodsNumArray[$i];
        }
        return $orderGoodsNum;
    }




    /**
    * 根据订单id查询订单信息
    *
    * param order_id:要查询的订单id
    *
     * @date 2016/01/07
    * @author Leen
    */
    public function getByOrderId($order_id){


        $order = Order::select('order.*','order_goods.*',
            'order.user_id',
            'order.order_id',
            'order.add_time'
        )
            ->leftJoin('order_goods', 'order.order_id', '=', 'order_goods.order_id')
            ->where('order.order_id',$order_id)->withTrashed()
            ->first();

        if ($order) {
            $order->orderGoods = OrderGoods::leftJoin('goods_eorder_info','order_goods.goods_sn','=','goods_eorder_info.goods_sn')
                ->leftJoin('brand','order_goods.brand_id','=','brand.brand_id')
                ->leftJoin('goods','order_goods.goods_id','=','goods.goods_id')
                ->where('order_goods.order_id',$order_id)
                ->select('order_goods.*','goods_eorder_info.goods_spec','goods_eorder_info.price','goods_eorder_info.ieType'
                    ,'goods_eorder_info.stockFlag','goods_eorder_info.batchNumbers','goods_eorder_info.tradeCountryCiq','goods_eorder_info.tradeCountryCus'
                    ,'goods_eorder_info.packageTypeCiq','goods_eorder_info.packageTypeCus','goods_eorder_info.currencyCiq','goods_eorder_info.currencyCus'
                    ,'goods_eorder_info.unitCiq','goods_eorder_info.unitCus','goods_eorder_info.originCountryCiq','goods_eorder_info.originCountryCus'
                    ,'goods_eorder_info.weight','goods_eorder_info.net_weight','goods_eorder_info.transportationWay','goods_eorder_info.shipCode','goods_eorder_info.checkStatus','goods_eorder_info.item_record_no','goods_eorder_info.gcode','goods_eorder_info.fir_proportion','goods_eorder_info.unitCus1','goods_eorder_info.sec_proportion','goods_eorder_info.unitCus2','goods_eorder_info.usage', 'brand.brand_name', 'goods.goods_bar_code')
                ->get();
        }else{
            throw new OrderServiceException('订单不存在');
        }//end if()

        return $order;


    }//end func getByOrderId()


    /**
    * 根据订单sn查询订单信息
    *
    * param order_sn:要查询的订单sn
    *
    * @date 2016/01/07
    * @author Leen
    */
    public function getByOrderSn($order_sn, $user_id=''){

       $query = Order::where('order_sn',$order_sn);

       if ($user_id) {
           $query = $query->where('user_id', trim($user_id));
       }
       $order = $query->first();

        if ($order){
            return $this->getByOrderId($order->order_id);
        }

        return null;

    }//end func getByOrderSn()



    /**
     * 取消订单
     * @param $order_id
     * @param $reason
     * @date 2016/01/07
     * @return mixed
     */
    public function cancel($order_id,$reason,$user_id=0){

        $order= Order::find($order_id);

        if (!$order) throw new OrderServiceException('订单不存在');
        if ($order->order_status!=1) throw new OrderServiceException('只有待支付的订单才能取消');


        //取消订单,返还库存  //TODO 返回库存的时候,商品删除了怎么办?

        $orderGoods = OrderGoods::where('order_id',$order->order_id)->get();

        DB::beginTransaction();//开启事务,开始批量操作

        try {


            foreach ($orderGoods as $orderGoodsItem){

                $goods = Goods::find($orderGoodsItem->goods_id);

                if (!$goods) throw new OrderServiceException('订单中商品不存在错误');

                /*$goods->goods_number += $orderGoodsItem->buy_number;

                $goods->save();*/
                $goods_sn = $goods->goods_sn;
                $goods_id = $goods->goods_id;
                $goods_stock = $orderGoodsItem->buy_number;
                $operation = 'plus';
                $describe = '取消订单返还库存';
                $this->stockService->updateStock($goods_id, $user_id, $goods_stock, $operation, $describe, $this->goodsStockHistoryService);

            }

            $order->order_status = 5;

            $order->cancel_time = date('Y-m-d H:i:s');
            $order->cancel_reason = $reason;


            $order->save();

            //返还优惠券
            if ($order->coupon_id) {

                UserCoupon::where('user_id', $order->user_id)->where('coupon_id', $order->coupon_id)->update(['use_time'=>null]);
            }


        }catch (OrderServiceException $ex ){
            DB::rollback();

            throw new OrderServiceException($ex->getMessage());
        }

        DB::commit();

        return true;



    }



    /**
     * 确认收货
     * @param $order_id
     * @date 2016/01/07
     * @return mixed
     */
    public function reciveGoods($order_id){

        $order= Order::find($order_id);

        if (!$order) throw new OrderServiceException('订单不存在');

        if ($order->order_status!=3) throw new OrderServiceException('订单不是已发货状态');


        $order->order_status = 4;

        $order->recive_goods_time = date('Y-m-d H:i:s');
        return $order->save();
    }


    /**
     * @param $order_id
     * @param $shippint_type
     */
    // public function shippingTarrif($order_id){
    public function shippingTarrif($order_id, $send_shipping_type, $version = ''){

        $order = $this->getByOrderId($order_id);

        if ($order->order_status!=2) throw new OrderServiceException('该订单不是待发货状态');

        if ($order->shipping_time) {
            $shipping_time = $order->shipping_time;
        }else{
            $shipping_time = date('Y-m-d H:i:s');
        }//end if()

        //1 第一步,推送物流
        try {
            // 第二步：判断是老版本还是新版本
            switch ($version) {
                case 'old':
                    $shipping_num = $this->etoClient->pushSingle($order, $shipping_time);
                    break;

                case 'new':
                    // 第三步：判断是推哪家物流快递
                    switch ($send_shipping_type) {

                        case '0':
                            throw new OrderServiceException('请选择物流');
                            break;

                        case '1':
                            // 申通
                            $shipping_num = $this->etoClientNew->pushSingle($order, $shipping_time);
                            break;

                        case '2':
                            // 圆通

                            // 获取圆通运单号
                            $shipping_num = $this->ytoClient->getYtoBillNumber($order);

                            // 推送圆通单号到海关
                            $this->ytoClient->pushSingle($order, $shipping_time, $shipping_num);

                            break;

                        default:
                            throw new OrderServiceException('不支持所选物流');
                            break;
                    }
                    break;

                default:
                    // $shipping_num = $this->etoClient->pushSingle($order, $shipping_time);
                    throw new OrderServiceException('请选择发货版本');
                    break;
            }

        }catch (EtoClientException  $e){

            throw new OrderServiceException($e->getMessage());
        }

        if ($shipping_num=='') throw new OrderServiceException('获取单号失败');

        //更新物流号
        switch ($send_shipping_type) {
            case '0':
                throw new OrderServiceException('请选择物流');
                break;

            case '1':
                // 申通
                $this->shipping($order_id,'eto',$shipping_num, $shipping_time);
                break;

            case '2':
                // 圆通
                $this->shipping($order_id,'yto',$shipping_num, $shipping_time);
                break;
        }


        return true;


    }



    /**
     * 配送
     * @param $order_id
     * @param $shipping_type
     * @param $shipping_num
     * @return mixed
     */
    public function shipping($order_id,$shipping_type,$shipping_num,$current_time){

        $order = Order::find($order_id);

        $order->shipping_type = $shipping_type;

        $order->shipping_num = $shipping_num;

        $order->shipping_time = $current_time;

        $order->order_status = 3;//改为已发货状态

        return $order->save();

    }

    public function refund($order_id,$refund_num,$refund_fee,$refund_reason,$refund_time){
        $order = Order::find($order_id);
        $order->refund_num = $refund_num;
        $order->refund_fee = $refund_fee;
        $order->refund_reason = $refund_reason;
        $order->refund_time = $refund_time;
        $order->order_status = 6;
        return $order->save();
    }


    /**
     * 推关
     * @param $order_id
     * @return mixed
     * @throws OrderServiceException
     */
    public function pushTarrif($order_id, $optType){

        $order = $this->getByOrderId($order_id);

        Log::info('开始推送订单['.$order_id.']至海关'.$order->toJson());

        $pushTarrif = $this->pushTarrifService->getByOrderId($order_id);


        if ($pushTarrif->push_tarrif_status==3) throw new OrderServiceException('该订单已经取消推关');

        try {
            //推送海关请求
            $current_time = date('Y-m-d H:i:s');
            //更新订单表推关状态
            $orders = Order::find($order_id);
            if ($orders) {
                if(empty($orders->push_tarrif_time)){

                    $orders->push_tarrif=1;
                    $orders->push_tarrif_time = $current_time;
                    $orders->save();

                }//end if()


                $user = User::find($order->user_id);

                $buyerRegNo = '';

                if ($user->phone) {

                    $buyerRegNo = $user->phone;
                }elseif ($user->email) {

                    $buyerRegNo = $user->email;
                }elseif ($user->user_name) {

                    $buyerRegNo = $user->user_name;
                }else{

                    throw new OrderServiceException('用户登录账号不存在');
                }

                try {

                    $this->etouchClient->push($order, $optType, $orders->shipping_time, $buyerRegNo);

                } catch (EtouchClientException $e) {

                    //将推关失败的信息存入订单推关信息表

                    $push_tarrif_status = 4;

                    $this->pushTarrifService->updatePushTarrif($order_id, $push_tarrif_status, $current_time, $e->getMessage());

                    throw new OrderServiceException($e->getMessage());

                }

            }//end if()



            //将推关成功的信息存入订单推关信息表
            $push_tarrif_status = 2;
            $this->pushTarrifService->updatePushTarrif($order_id, $push_tarrif_status, $current_time, '推关成功');

            Log::info('成功推送订单['.$order_id.']至海关'.$order->toJson());

            return true;


        }catch (EtouchClientException $e){

            Log::info('失败推送订单['.$order_id.']至海关,失败原因:'.$e->getMessage());


            //推送失败,异常保存至到推关失败记录里面啊
            $push_tarrif_status = 4;
            $this->pushTarrifService->updatePushTarrif($order_id, $push_tarrif_status, $e->getMessage());
            throw new OrderServiceException($e->getMessage());

        }




    }

    /**
     * 推关（旧版）
     * @param $order_id
     * @return mixed
     * @throws OrderServiceException
     */
    public function pushTarrifOld($order_id, $optType){

        $order = $this->getByOrderId($order_id);

        Log::info('开始推送订单['.$order_id.']至海关'.$order->toJson());

        $pushTarrif = $this->pushTarrifService->getByOrderId($order_id);


        if ($pushTarrif->push_tarrif_status==3) throw new OrderServiceException('该订单已经取消推关');

        try {
            //推送海关请求
            $current_time = date('Y-m-d H:i:s');
            //更新订单表推关状态
            $orders = Order::find($order_id);
            if ($orders) {
                if(empty($orders->push_tarrif_time)){

                    $orders->push_tarrif=1;
                    $orders->push_tarrif_time = $current_time;
                    $orders->save();

                }//end if()


                $user = User::find($order->user_id);

                $buyerRegNo = '';

                if ($user->phone) {

                    $buyerRegNo = $user->phone;
                }elseif ($user->email) {

                    $buyerRegNo = $user->email;
                }elseif ($user->user_name) {

                    $buyerRegNo = $user->user_name;
                }else{

                    throw new OrderServiceException('用户登录账号不存在');
                }

                $this->etouchClientOld->push($order, $optType, $orders->shipping_time, $buyerRegNo);

            }//end if()



            //将推关成功的信息存入订单推关信息表
            $push_tarrif_status = 2;
            $this->pushTarrifService->updatePushTarrif($order_id, $push_tarrif_status, $current_time, '推关成功');

            Log::info('成功推送订单['.$order_id.']至海关'.$order->toJson());

            return true;


        }catch (EtouchClientException $e){

            Log::info('失败推送订单['.$order_id.']至海关,失败原因:'.$e->getMessage());


            //推送失败,异常保存至到推关失败记录里面啊
            $push_tarrif_status = 4;
            $this->pushTarrifService->updatePushTarrif($order_id, $push_tarrif_status, $e->getMessage());
            throw new OrderServiceException($e->getMessage());

        }




    }

    /**推送支付宝单号
     * @param $order_id
     * @throws Exception
     * @throws OrderServiceException
     */

    function pushAlipay($order_id){

        $order = Order::find($order_id);

        if ($order->pay_push==1) throw new OrderServiceException('改支付单已成功推送');

        //支付流水号
        $out_trade_no = $order->order_sn;
        //支付单号
        $trade_no = $order->pay_num;
        //支付价格
        $pay_price = $order->pay_price;

        try {
            Log::info('开始推送订单['.$order_id.']至支付宝'.$order->toJson());

            $alipayPush = $this->alipayCustom->request($out_trade_no, $trade_no, $pay_price);
            //支付宝推送成功之后将推送是否成功的状态以及推送成功的时间存入到数据库
            $push_status = $alipayPush?1:2;
            $order->update(['pay_push'=>$push_status, 'pay_push_success_time'=>date('Y-m-d H:i:s')]);

            Log::info('成功推送订单['.$order_id.']至支付宝'.$order->toJson());

            return true;

        } catch (AlipayCustomsException $e) {

            Log::info('失败推送订单['.$order_id.']至支付宝,原因:'.$e->getMessage());

            throw new OrderServiceException($e->getMessage());
        }

    }





    function getStatus($order_id){

       $order = Order::find($order_id);

        return $order->order_status;

    }//end func getError()


    /**支付成功回调
     * @param $order_sn
     * @param $pay_type
     * @param $pay_num
     * @param $pay_time
     * @param $log
     * @return mixed
     */
    public function orderPayBack($order_sn,$pay_type,$pay_num,$pay_time,$log=''){

       $order = $this->getByOrderSn($order_sn);
       $order = Order::find($order->order_id);

            $order->order_status=2;//更改状态,
            $order->pay_type=$pay_type;//支付类型,
            $order->pay_num=$pay_num;
            $order->pay_time=$pay_time;

        $order->save();


        return $order->order_id;
    }


    public function getCustomsClearance($order_id){

        $order = Order::find($order_id);

        //$order->order_sn = 'G3257182305469d';
//        //$return = $this->customsClearance->sendPost($order->order_sn,$order->shipping_num,time());
//        $arr0 = ['order_sn'=>'G3292044795279d','shipping_num'=>'220689843582'];
//        $arr1 = ['order_sn'=>'G3257182305469d','shipping_num'=>'220689843583'];
//        $arrs[0] = (object)$arr0;
//        $arrs[1] = (object)$arr1;
        $return = $this->customsClearance->sendPost([$order]);
        if (key_exists($order->order_sn,$return)) return $return[$order->order_sn];
        return ;

    }


    /**
     * 生成订单号
     *
     * @return string
     */
    public  function makeOrderSn() {
        $year_code = array('A','B','C','D','E','F','G','H','I','J');
        $order_sn = $year_code[intval(date('Y'))-2010].strtoupper(dechex(date('m'))).date('d').substr(time(),-5).substr(microtime(),2,5).sprintf('d',rand(0,99));
        return $order_sn;
    }


    /**
     * 生成支付单号
     *
     * @return string
     */
    public  function makePaySn() {
        $year_code = array('A','B','C','D','E','F','G','H','I','J');
        $order_sn = $year_code[intval(date('Y'))-2010].strtoupper(dechex(date('m'))).date('d').substr(time(),-5).substr(microtime(),2,5).sprintf('d',rand(0,99));
        return $order_sn;
    }
//
//    /**
//     * 获取清关状态
//     */
//    public function getCustomsClearanceStatus($order_sn,$shipping_num,$request_time){
//
//        return $this->customsClearance->sendPost($order_sn,$shipping_num,$request_time);
//    }


    /**
     * [订单删除]
     * @param  [type] $order_id [订单id]
     * @param  [type] $user_id  [用户id]
     * @date 2016/04/07
     * @author Leen
     */
    public function destoryOrder($order_id, $user_id){

        $orders = Order::find($order_id);

        if ($orders) {

            $users = User::find($user_id);
            if ($users) {

                $order = Order::where('order_id', $order_id)->where('user_id', $user_id)->first();
                if ($orders) {
                    $order_status = $orders->order_status;
                    switch ($order_status) {
                        case 4:
                            //判断订单是否进行过退货操作，如果有则只有"不予受理"和"已取消"状态的售后单才可以删除（退货商品的售后服务状态：1:待确认; 2:已受理；3:处理完毕；4:不予受理；5:已取消；）
                        case 5:
                            $status = $orders->delete();
                            return $status;
                            break;

                        default:
                            throw new OrderServiceException('只有已取消的订单才能够删除');
                            break;
                    }//end switch()

                }else {
                    throw new OrderServiceException('订单id与用户不匹配');
                }//end if()

            }else{

                throw new OrderServiceException('用户不存在');
            }//end if()

        }else{

            throw new OrderServiceException('订单不存在或已删除');
        }//end if()


    }//end func destoryOrder()


    public function coupon(){

        //$this->couponService->();


    }


    /**微信支付报关
     * @param $order_id
     * @throws Exception
     * @throws OrderServiceException
     */
    function pushWxpay($order_id){

        $order = Order::find($order_id);

        if ($order->pay_push==1) throw new OrderServiceException('该支付单已成功推送');

        //支付流水号
        $out_trade_no = $order->order_sn;

        //支付单号
        $trade_no = $order->pay_num;

        //支付价格
        $pay_price = $order->pay_price;

        try {

            Log::info('开始推送订单['.$order_id.']至微信支付'.$order->toJson());

            $wxpay = new Wxpay(config('latrell-wxpay'));

            $pushCustoms = $wxpay->pushCustoms();


            $customs = config('eorderinfo.customs_type_wx');            //海关代码

            $input = new PushCustoms();

            $input->setOutTradeNo($out_trade_no);

            $input->setTransactionId($trade_no);

            $input->setCustoms($customs);


            //有拆单或者重新报关时必填
            // $again_push = 1;
            if(isset($again_push)){

                $fee_type = 'CNY';

                /*$sub_order_no = $out_trade_no;

                $order_fee = $pay_price;

                $transport_fee = $order->shipping_fee;

                $product_fee = $order->order_price;

                $duty = $order->order_tariff_fee;*/


                $input->setSubOrderNo($sub_order_no);           //商户子订单号，如有拆单则必传

                $input->setFeeType($fee_type);                  //微信支付订单支付时使用的币种，暂只支持人民币CNY,如有拆单则必传。

                $input->setOrderFee($order_fee);                //子订单金额，以分为单位，不能超过原订单金额，order_fee=transport_fee+product_fee（应付金额=物流费+商品价格），如有拆单则必传。

                $input->setTransportFee($transport_fee);        //物流费用，以分为单位，如有拆单则必传。

                $input->setProductFee($product_fee);            //商品费用，以分为单位，如有拆单则必传。

                // $input->setDuty($duty);                      //关税，以分为单位
            }

            //以下字段在微信缺少用户信息时必传，如果商户上传了用户信息，则以商户上传的信息为准
            $no_user_info = 1;
            if (isset($no_user_info)) {

                $cert_type = 'IDCARD';

                $cert_id = $order->id_card;

                $name = $order->consignee;

                $input->setCertType($cert_type);            //证件类型,暂只支持身份证

                $input->setCertId($cert_id);                //证件号码

                $input->setName($name);                     //姓名
            }

            if (isset($customs) && $customs!='NO') {

                // $mch_customs_no = config('eorderinfo.cbeCode');
                // $mch_customs_no = config('eorderinfo.ecpCodeCus');
                $mch_customs_no = config('eorderinfo.ecpCodeCus_new');

                $input->setMchCustomsNo($mch_customs_no);
            }

            $result = $pushCustoms->push($input);

            Log::info('推送结果'.json_encode($result));

            // dd($result);

            if (isset($result['return_code']) && isset($result['result_code']) && $result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

                $push_status = 1;
            }else{

                $push_status = 2;
            }

            //微信支付推送成功之后将推送是否成功的状态以及推送成功的时间存入到数据库，1：成功；2：失败
            $order->update(['pay_push'=>$push_status, 'pay_push_success_time'=>date('Y-m-d H:i:s')]);

            Log::info('成功推送订单['.$order_id.']至微信支付'.$order->toJson());

            if ($push_status==2) {

                if ($result['return_code']=='FAIL') {

                    throw new OrderServiceException($result['result_code']);
                }elseif ($result['return_code']=='SUCCESS' && $result['result_code'] == 'FAIL'){

                    throw new OrderServiceException($result['err_code_des']);
                }
            }

            return true;

        } catch (AlipayCustomsException $e) {

            Log::info('失败推送订单['.$order_id.']至微信支付,原因:'.$e->getMessage());

            throw new OrderServiceException($e->getMessage());
        }

    }





//    function refundAlipay($order_id){
//
//        $order = Order::find($order_id);
//
//        if ($order->refund_status==2) throw new OrderServiceException('该订单已退款');
//
//
//    }

//    function refundWxpay($order_id){
//
//        $order = Order::find($order_id);
//        if ($order->refund_status==2) throw new OrderServiceException('该订单已退款');
//
//        try{
//            $wxpay = new Wxpay(config('latrell-wxpay'));
//            $refund = $wxpay->refund();
//
//            $input = new Refund();
//
//            $out_trade_no = $order->order_sn; //商户订单号
//            $out_refund_no = $order->order_sn;  //商户退款单号
//            $total_fee = $order->pay_price; //总金额
//            $refund_fee = $order->pay_price; //退款金额
//
//            $input->setOutTradeNo($out_trade_no);
//            $input->setOutRefundNo($out_refund_no);
//            $input->setTotalFee($total_fee);
//            $input->setRefundFee($refund_fee);
//            $input->setOpUserId(config('latrell-wxpay')['mchid']); //操作员
//
//            $result = $refund->refund($input);
//
//            Log::info('退款申请结果'.json_encode($result));
//
//            if (isset($result['return_code']) && isset($result['result_code']) && $result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
//
//                Log::info('订单['.$order_id.']微信退款申请成功');
//            }
//
//
//        }catch (WxpayException $e){
//
//            Log::info('订单['.$order_id.']微信退款申请失败,原因:'.$e->getMessage());
//            throw new OrderServiceException($e->getMessage());
//        }
//
//    }


}